package com.wohuijituan.whcsmerchant.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.adapter.OrderListAdapter;
import com.wohuijituan.whcsmerchant.bean.CommonBean;
import com.wohuijituan.whcsmerchant.bean.OrderListBean;
import com.wohuijituan.whcsmerchant.callback.CommonCallBack;
import com.wohuijituan.whcsmerchant.callback.OrderListCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;
import com.wohuijituan.whcsmerchant.utils.MyUtile;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class OrderStateFragment extends MyBaseFragment {
    private int orderState;

    public static OrderStateFragment newInstance(int orderState){
        OrderStateFragment fragment = new OrderStateFragment();
        Bundle data = new Bundle();
        data.putInt("orderState",orderState);
        fragment.setArguments(data);
        return fragment;
    }
    private static final String TAG = "OrderStateFragment";
    private static final int GetOrderList_OK = 100;
    private static final int GetOrderList_Error = 101;
    private static final int SetOrderState_OK = 110;

    private int nowPage = 1;//当前显示页数
    private int totalPage;//订单总页数
    private int pageNumber = 5;//每页显示个数
    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    public static final int ORDER_STATE_UNRECEIVE = 20;//已付款
    public static final int ORDER_STATE_PREPARE = 30;//备货中
    public static final int ORDER_STATE_DELIVER = 31; //配送中
    public static final int ORDER_STATE_DELIVER_OVER = 32;//已送达
    public static final int ORDER_STATE_DONE = 40;//用户已收货
    public static final int ORDER_STATE_REFUND = 70;//申请退款
    public static final int ORDER_STATE_REFUND_OVER = 80;//退款完成
    private PullToRefreshListView myPullListView;
    private List<OrderListBean.DataEntity.OrderEntity> orderList;
    private OrderListAdapter mAdapter;
    private OrderListBean.DataEntity.OrderEntity orderDeal;//当前正在处理的订单
    @Override
    public View createMyView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.fragment_order_undone, container, false);
            myPullListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list_order_undone);
            myPullListView.setMode(PullToRefreshBase.Mode.BOTH);
            initData();
            initListener();
            orderListRequest(1, pageNumber,orderState);

        return view;
    }

    private void initData() {
        orderState = getArguments().getInt("orderState");
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        orderList = new ArrayList<>();
        mAdapter = new OrderListAdapter(ctx,orderList);
        myPullListView.setAdapter(mAdapter);

    }

    private void initListener() {
        mAdapter.setItemBtnClickListener(new OrderListAdapter.MyOnItemBtnClickListener() {
            @Override
            public void onClick(int position) {
                orderDeal = orderList.get(position);
                int orderStatus = orderDeal.getO_Status();//订单状态
                String orderNum = orderDeal.getO_GUID();//订单编号
                operateOrder(orderNum,orderStatus);
                LogUtils.e(TAG, position + "");
                showToast(ctx, "点击位置:" + position);
            }
        });
        myPullListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                orderListRequest(1, pageNumber,orderState);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (nowPage < totalPage) {
                    //得到下一页数据
                    orderListRequest(nowPage + 1, pageNumber,orderState);
                }else {

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showToast(ctx,"已经是最后一页");
                            myPullListView.onRefreshComplete();
                        }
                    },1000);

                }
            }
        });
    }
    /**
     * 操作订单的方法
     * @param orderState 被操作订单的状态
     */
    private void operateOrder(final String orderNum, final int orderState){
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle("提示");
        builder.setNegativeButton("取消",null);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setOrderStateRequest(orderNum,orderState);
            }
        });
        switch (orderState){
            case ORDER_STATE_UNRECEIVE:
                //  已付款订单
                builder.setMessage("是否确认接单?");
                break;
            case ORDER_STATE_PREPARE:
                //  备货中订单
                builder.setMessage("是否确认发货?");
                break;
            case ORDER_STATE_DELIVER:
                //  送货中订单
                builder.setMessage("是否确认已送达?");
                break;
            case ORDER_STATE_REFUND:
                // 用户申请退款订单
                builder.setMessage("是否确认退款申请?");
                break;
            default:
                showToast(ctx,"订单状态错误:"+orderState);
        }
        builder.show();
    }
    /**
     * 网络请求设置订单状态
     * @param orderNum 订单号
     * @param state 要设置的订单状态
     */
    private void setOrderStateRequest(String orderNum, int state){
        showDialog(ctx);
        String strUrl = "";
        switch (state){
            case ORDER_STATE_UNRECEIVE://未接单的订单
                strUrl = Urls.OperateOrder_Receive;
                break;
            case ORDER_STATE_PREPARE://已接单未发货的订单
                strUrl = Urls.OperateOrder_Deliver;
                break;
            case ORDER_STATE_DELIVER://已发送未送达的订单
                strUrl = Urls.OperateOrder_DeliverOver;
                break;
            case ORDER_STATE_REFUND://申请退款的订单
                strUrl = Urls.OperateOrder_AgreeRefund;
                break;
        }
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.OrderStateSet_Number,orderNum);
        String sign = MyUtile.getEncodeSign(ParamsKey.MD5_Start,ParamsKey.MD5_End,
                myApplication.getUserKey(),orderNum);
        params.addStringRequest(ParamsKey.Sign,sign);
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }
            @Override
            public void onResponse(CommonBean response, int id) {
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GetOrderList_OK;
                    handler.sendEmptyMessage(SetOrderState_OK);
                } else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
            }
        });
    }
    /**
     * 网络请求订单
     */
    private void orderListRequest(int pageIndex,int pageNumber,int orderState) {
        showDialog(ctx);
        String strUrl = Urls.OrderList;
        LogUtils.e(TAG, strUrl);
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.OrderList_PageIndex, pageIndex + "");
        params.addStringRequest(ParamsKey.OrderList_State, orderState + "");
        params.addStringRequest(ParamsKey.OrderList_Rows, pageNumber + "");
        String sign = MyUtile.getEncodeSign(ParamsKey.MD5_Start,ParamsKey.MD5_End,
                myApplication.getUserKey(),orderState+"",pageIndex+"",pageNumber+"");
        params.addStringRequest(ParamsKey.Sign,sign);
        myOkHttpUtils.postRequest(strUrl, params, new OrderListCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                myPullListView.onRefreshComplete();
            }
            @Override
            public void onResponse(OrderListBean response, int id) {
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GetOrderList_OK;
                    msg.obj = response;
                    handler.sendMessage(msg);
                } else if (response.getState() == 0) {
                    showToast(ctx, "暂无订单");
                } else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
                myPullListView.onRefreshComplete();
            }
        });
    }


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case GetOrderList_OK:
                    OrderListBean orderListBean= (OrderListBean) msg.obj;
                    nowPage = orderListBean.getData().getPageIndex();
                    totalPage = orderListBean.getData().getPageCount();
                    LogUtils.e(TAG,nowPage+"");
                    if (nowPage ==1){
                        mAdapter.replace(orderListBean.getData().getData());
                    }else if (nowPage>1){
                        mAdapter.addAll(orderListBean.getData().getData());
                    }
                    dismissDialog();
                    break;
                case SetOrderState_OK://TODO 对当前操作的订单数据进行处理
                    dismissDialog();
                    orderListRequest(1, pageNumber,orderState);//再次请求订单列表
                    break;
            }
        }
    };

}
